package org.dragonnova.meetingserver.server.service;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import org.dragonnova.meetingserver.R;
import org.dragonnova.meetingserver.server.activity.MainActivity;
import org.dragonnova.meetingserver.server.application.TransBoxApplication;
import org.dragonnova.meetingserver.utils.LogUtil;
import org.dragonnova.meetingserver.utils.PackageUtil;

/**
 * Created by hucn on 2016/3/16.
 * Description:
 */
public class RestartService extends Service {


    private PowerReceiver powerReceiver;
    private HomeKeyRecevier homeReceiver;
    private NotificationManager notificationManager;

    @SuppressLint("HandlerLeak")
    private Handler restartHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            startActivity();
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!TransBoxApplication.getInstance().isActivityVisible()) {
                        sendEmptyMessage(1);
                    }
                }
            },100);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.eee("service start");
        //service启动的时候有没有activity在前台，没有的话启动一个activity
        if (!TransBoxApplication.getInstance().isActivityVisible()) {
            LogUtil.eee("check if there is visible activity when the service starts, if not, start a new one");
            startActivity();
        }
        //监听是否有应用是否在前台
        TransBoxApplication.getInstance().setactivityVisibleListener(new TransBoxApplication.activityVisibleListener() {
            @Override
            public void onInvisible() {
                LogUtil.eee("if no activity is visible, then start a activity quickly");
                restartHandler.sendEmptyMessage(1);
            }
        });

        //一开始就点亮屏幕
        ScreenOnAndLockOff(this);

        //注册监听home键的广播
        IntentFilter homeFilter = new IntentFilter();
        homeFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        homeReceiver = new HomeKeyRecevier();
        registerReceiver(homeReceiver, homeFilter);

        //注册监听屏幕亮暗和解锁的广播
        IntentFilter powerFilter = new IntentFilter();
        powerFilter.addAction(Intent.ACTION_SCREEN_ON);
        powerFilter.addAction(Intent.ACTION_SCREEN_OFF);
        powerFilter.addAction(Intent.ACTION_USER_PRESENT);
        powerReceiver = new PowerReceiver();
        registerReceiver(powerReceiver, powerFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.eee("return start_sticky in onStartCommand");
        //service在前台注册一个通知，尽可能保证service不被杀死
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("PowerListener")
                .setContentText("not clear this notification").setOngoing(true);
        notificationManager.notify(100, notifyBuilder.build());
        //service被系统杀死后会被重启
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.eee("service destroy");
        notificationManager.cancel(100);
        unregisterReceiver(powerReceiver);
        unregisterReceiver(homeReceiver);
    }

    /**
     * home键的监听
     */
    class HomeKeyRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.eee("home key broadcast received");
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                        // 按home键
                        LogUtil.eee("HomeKey pressed");
                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                        // 长按home键
                        LogUtil.eee("HomeKey pressed for a long time");
                    }
                    startActivity();
                }
            }
        }
    }

    /**
     * Created by hucn on 2016/3/16.
     * Description:这个类用来监听屏幕亮和暗，还有用户的解锁动作，ACTION_SCREEN_ON和ACTION_SCREEN_OFF只能在动态注册中才能起作用
     */
    public class PowerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.eee(" power key broadcast received");
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                //只能用于动态注册
                LogUtil.eee(" screen off");
                ScreenOnAndLockOff(context);
            } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
                //只能用于动态注册
                LogUtil.eee(" screen on");
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                //可以用于动态和静态注册，当用户重新唤醒手持设备时触发
                LogUtil.eee(" user present");
                Intent aIntent = new Intent(context, MainActivity.class);
                aIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(aIntent);
            }

            boolean serviceStatus = PackageUtil.getServiceStatus(context, "com.example.hucn.powerdemo.RestartService");
            if (!serviceStatus) {
                Intent sIntent = new Intent(context, RestartService.class);
                context.startService(sIntent);
            }
        }
    }

    private void ScreenOnAndLockOff(Context context) {
        //唤醒屏幕
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "SimpleTimer");
        mWakelock.acquire();
        mWakelock.release();
        //去除锁屏
        /*KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("");
        keyguardLock.disableKeyguard();*/
    }

    /**
     * 启动一个activity
     */
    public void startActivity() {
        Intent aIntent = new Intent(this, MainActivity.class);
        aIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        aIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        this.startActivity(aIntent);
    }
}
